import sys
import os
from datetime import datetime
import glob


class FileOP:
    def __init__(self, rootPath: str = "./data"):
        self.root = rootPath
        os.path.exists(self.root) or os.makedirs(self.root)
        self.raw = os.path.join(self.root, "raw")
        self.post = os.path.join(self.root, "post")
        os.path.exists(self.raw) or os.makedirs(self.raw)
        os.path.exists(self.post) or os.makedirs(self.post)
        print("File data folder creted at:", self.root)

    def GetFileName(self, time: datetime) -> str:
        fileName = time.strftime("%Y-%m-%d-%H-%M")
        return fileName

    def GetAbsFilePath(self, fileName: str, type: str, fileType: str = ".data") -> str:
        return os.path.join(
            self.raw if type == "raw" else self.post, fileName + fileType
        )

    def GlobFilePathInRange(
        self, start: datetime, end: datetime, type: str, fileType: str = ".csv"
    ) -> list[str]:
        files = []
        globPath = (
            os.path.join(self.raw, "*" + fileType)
            if type == "raw"
            else os.path.join(self.post, "*" + fileType)
        )
        globFiles = glob.glob(globPath)
        for file in globFiles:
            fileName = os.path.basename(file)
            fileTime = datetime.strptime(fileName, "%Y-%m-%d-%H-%M" + fileType)
            if start <= fileTime <= end:
                files.append(file)
        return files
